<template>
  <div style="padding: 10px 0">
    <el-input placeholder="请输入部门名" style="width: 200px" :suffix-icon="Search"
              v-model="departName"></el-input>
    <el-button class="ml-5" type="primary" @click="load">搜索</el-button>
    <el-button type="warning" @click="reset">重置</el-button>
  </div>
  <div style="margin: 10px 0">
    <el-button type="primary" @click="handleAdd">新增<i class=" el-icon-circle-plus-outline"></i>
    </el-button>
    <el-button type="danger" :icon="Delete" @click="open1" class="del">批量删除<i class=" el-icon-remove-outline"></i>
    </el-button>
  </div>

  <el-table
      :data="DepartmentInfo"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      :row-style="tableRowClassName"
      default-expand-all
      row-key="ID"
  >
    <el-table-column type="selection" width="55"></el-table-column>
    <el-table-column prop="ChnName" label="使用单位中文名称" />
    <el-table-column prop="EngName" label="使用单位英文名称"/>
    <el-table-column prop="Email" label="邮箱"/>
    <el-table-column prop="Phone" label="电话"/>
    <el-table-column prop="cntAdd" label="地址"/>
    <el-table-column prop="isUse" label="是否投入正常运行" width="160"/>
    <el-table-column label="操作" width="200" align="center">
      <template #default="scope">
        <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
        <el-button type="danger" @click="del(scope.row.uintID)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-dialog title="新增使用单位" v-model="dialogDepartmentFormVisible">
    <el-form ref="userForm" :model="form" :rules="rules">
      <el-form-item label="使用单位中文名称" :label-width="formLabelWidth" prop="unitChnName">
        <el-input v-model="form.unitChnName"></el-input>
      </el-form-item>
      <el-form-item label="使用单位英文名称" :label-width="formLabelWidth" prop="unitEngName">
        <el-input v-model="form.unitEngName"></el-input>
      </el-form-item>
      <el-form-item label="平台版本号" :label-width="formLabelWidth" prop="versionNum">
        <el-input v-model="form.versionNum"></el-input>
      </el-form-item>
      <el-form-item label="部门邮箱地址" :label-width="formLabelWidth" prop="departEmail">
        <el-input v-model="form.departEmail"></el-input>
      </el-form-item>
      <el-form-item label="部门电话" :label-width="formLabelWidth" prop="departPhone">
        <el-input v-model="form.departPhone"></el-input>
      </el-form-item>
      <el-form-item label="是否投入正常运行" :label-width="formLabelWidth" prop="isUse">
        <el-radio-group v-model="form.isUse">
          <el-radio label="是"/>
          <el-radio label="否"/>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogDepartmentFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">
          确 定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {Search, DocumentChecked, Delete} from '@element-plus/icons-vue'
import {onMounted, reactive, ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import type {FormRules, FormInstance} from 'element-plus'
import axios from "axios";
import {transformDepartJson} from "@/utils/transformedJson";

interface TransformedDepartment {
  ID: number;
  ChnName: string;
  EngName: string;
  Phone: string;
  Email: string;
  children?: TransformedDepartment[];
  cntAdd : string;
  isUse : string;
}
const departName = ref('')
const formLabelWidth = '140px'

const DepartmentInfo = ref<TransformedDepartment[]>([])
let dialogDepartmentFormVisible = ref(false)
let total = ref(1)
let form = ref({
})
const open1 = () => {
  ElMessageBox.alert('确定批量删除吗？', '', {
    confirmButtonText: '确定',
    showCancelButton: true,
    cancelButtonText: '我再想想',
    type: "warning"
  }).then(() => {
    delBatch();
  }).catch(() => {
    ElMessage.info("已取消删除")
  })
}
const handleAdd = () => {
  dialogDepartmentFormVisible.value = true
  form.value = {}
}
const load = () => {
  axios.get('http://localhost:8080/departmentinfo/all')
      .then(
          res => {
            if (res.data){
              res.data.forEach((item: []) => {
                item.isUse = item.isUse ? '是' : '否';
                if(item.children){
                  item.children.forEach((item1: []) => {
                    item1.isUse = item1.isUse ? '是' : '否';
                  })
                }
              })
            }
            DepartmentInfo.value = transformDepartJson(res.data)
            console.log(DepartmentInfo.value)
          }
      ).catch(e =>{
    console.log(e)
  })
}
onMounted(() => {
  load();
})
const ids = ref([])
const handleSelectionChange = (val: any) => {
  ids.value = val.map((item) => item.uintID)
  console.log(ids.value)
};
const delBatch = () => {
  axios.post('http://localhost:8080/departmentinfo/page').then(res => {
    if (res) {
      ElMessage.success("批量删除成功")
      load()
    } else {
      ElMessage.warning("批量删除失败")
    }
  })
};
const userForm = ref(null)
const save =  async () => {
  await userForm.value.validate((valid: boolean) => {
    if (valid) {
      if (form.value.isUse == '是') {
        form.value.isUse = true
      } else form.value.isUse = false
      axios.post('http://localhost:8080/departmentinfo', form.value).then(res => {
        if (res) {
          ElMessage.success("保存成功")
          dialogDepartmentFormVisible.value = false;
          userForm.value.resetFields()
          load()
        } else {
          ElMessage.warning("保存失败")
        }
      })
    } else {
      ElMessage.warning( "请修改正确的数据格式！");
    }
  })
}
const pageSize = ref(10)
const pageNum = ref(1)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (newPageSize) => {
  pageSize.value = newPageSize
  load()
}
const handleCurrentChange = (newPageNum) => {
  pageNum.value = newPageNum
  load()
}
const reset = () => {
  VersionNum.value = ''
  UnitName.value = ''
  load()
}
const del = (unitID) => {

  axios.delete('http://localhost:8080/departmentinfo/' + unitID).then(res => {
    if (res) {
      ElMessage.success("删除成功")
      load()
    } else {
      ElMessage.error("删除失败")
    }
  })
}
const handleEdit = (row) => {
  form = row
  dialogDepartmentFormVisible.value = true
}


const rules = reactive<FormRules>({
  unitChnName: [
    {required: true, message: "使用单位中文名称不能为空", trigger: "blur"}
  ],
  unitEngName: [
    {required: true, message: "使用单位英文名称不能为空", trigger: "blur"}
  ],
  versionNum: [
    {required: true, message: "平台版本号不能为空", trigger: "blur"}
  ],
  isUse: [
    {required: true, message: "是否投入正常运行不能为空", trigger: "change"}
  ],
  departPhone: [
    {required: true, message: "使用单位电话不能为空", trigger: "blur"}
  ],
  departEmail: [
    {required: true, message: "使用单位邮箱不能为空", trigger: "blur"}
  ]
})

const tableRowClassName = ({
                             row
                           }: {
  row: any
}) => {
  if (row.isUse === "否") {
    return {
      backgroundColor: '#fdf6ec'
    }
  } else if (row.isUse === "是") {
    return {
      backgroundColor: '#f0f9eb'
    }
  }
  return ''
}
</script>


<style scoped>
.ml-5 {
  margin-left: 10px;
}

.pagination-block {
  margin-left: 25%;
}
</style>